package util;

import entity.Car.model.Car;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by vanches on 13.1.15.
 */
public class CreatePDF {

    public void exportListCar(List<Car> listCar){
        Map<String, Object> map = new HashMap<String, Object>();
        Calendar calendar = Calendar.getInstance();

        List<CarExporter> carExporters=new ArrayList<CarExporter>();
        for(int i=0; i<listCar.size();i++){
            calendar.setTime (listCar.get(i).getTransport().getDate());
            String description=listCar.get(i).getTransport().getBrand().getNameEn()+" "+
            listCar.get(i).getModel().getNameEn()+", "+listCar.get(i).getTransport().getColor().getNameEn()+", "+
                    listCar.get(i).getBodyType().getNameRu()+", "+
                    listCar.get(i).getTypeEngine().getNameRu()+" "+listCar.get(i).getValueEngine();



            carExporters.add(new CarExporter(
                    Integer.toString(listCar.get(i).getId()),
                   description,
                    Integer.toString(calendar.get(Calendar.YEAR)),
                   Double.toString( listCar.get(i).getTransport().getPrice())+" "+listCar.get(i).getTransport().getCurrency().getShortnameEn()

            ));
        }




        File jasper = new File("/home/vanches/report2.jasper");
        try {
            export(map,jasper,carExporters);
        } catch (JRException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void exportCar(Car car){

    }

    private void export(Map map, File jasper, List<CarExporter> cars)throws JRException, IOException{
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasper.getPath(), map, new JRBeanCollectionDataSource(cars));
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        httpServletResponse.addHeader("Content-disposition", "attachment; filename=filePDF.pdf");
        ServletOutputStream stream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, stream);


        stream.flush();
        stream.close();
        FacesContext.getCurrentInstance().responseComplete();
    }


}
